package com.example.cloud.service.business.medical.impl;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.TreatPlanCourseDetailsRepository;
import com.example.cloud.dao.business.medical.TreatPlanCourseRepository;
import com.example.cloud.dao.finance.ChargeDetailsRepository;
import com.example.cloud.model.basic.CourseDetails;
import com.example.cloud.model.business.medical.TreatPlanCourse;
import com.example.cloud.model.business.medical.TreatPlanCourseDetails;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.ChargeDetails;
import com.example.cloud.model.member.Member;
import com.example.cloud.service.basic.info.CourseDetailsService;
import com.example.cloud.service.basic.info.MemberService;
import com.example.cloud.service.business.medical.TreatPlanCourseService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class TreatPlanCourseServiceImpl implements TreatPlanCourseService {

    private static final Logger logger = Logger.getLogger(TreatPlanCourseServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private CourseDetailsService courseDetailsService;

    @Autowired
    private TreatPlanCourseRepository treatPlanCourseRepository;

    @Autowired
    private TreatPlanCourseDetailsRepository treatPlanCourseDetailsRepository;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ChargeDetailsRepository chargeDetailsRepository;

    @Override
    public TreatPlanCourse findOne(Long id) {
        return treatPlanCourseRepository.findOne(id);
    }

    @Override
    @Transactional
    public void doSave(List<TreatPlanCourse> records, Long patientId) {
        for (TreatPlanCourse record : records) {
            record.setId(null);
            record.setPatientId(patientId);
            // 设置会员信息
            ChargeDetails chargeDetails = new ChargeDetails();
            Member member = memberService.findByPatientId(patientId);
            if(member != null){
                record.setMemberId(member.getId());
                chargeDetails.setMemberId(member.getId());
            }
            record.setTotalPrice(record.getPrice().multiply(new BigDecimal(record.getQuantity())));
            record.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            record.setCreationTime(null);
            BusinessUtil.appendRecord(record);
            treatPlanCourseRepository.save(record);

            // 生成明细
            List<CourseDetails> details = courseDetailsService.findAllByCourseId(record.getCourseId());
            for (CourseDetails detail : details) {
                TreatPlanCourseDetails courseDetails = new TreatPlanCourseDetails();
                courseDetails.setPatientId(record.getPatientId());
                courseDetails.setMemberId(record.getMemberId());
                courseDetails.setComplaintId(record.getComplaintId());
                courseDetails.setCourseId(record.getId());
                courseDetails.setCourseName(record.getCourseName());
                courseDetails.setItemId(detail.getItemId());
                courseDetails.setItemName(detail.getItemName());
                courseDetails.setPrice(detail.getPrice());
                // 明细数量=基础疗程明细的治疗次数*购买疗程的数量
                courseDetails.setQuantity(detail.getQuantity() * record.getQuantity());
                courseDetails.setTotalPrice(detail.getPrice().multiply(new BigDecimal(courseDetails.getQuantity())));
                courseDetails.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
                courseDetails.setCreationTime(null);
                BusinessUtil.appendRecord(courseDetails);
                treatPlanCourseDetailsRepository.save(courseDetails);
            }

            // 创建收费
            generateChargeDetails(record, patientId, chargeDetails);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void generateChargeDetails(TreatPlanCourse record, Long patientId, ChargeDetails details){
        details.setPatientId(patientId);
        details.setBusinessId(record.getId());
        details.setBusinessType(StateConstants.CHARGE_BUSINESS_TYPE_COURSE);
        details.setChargeType(StateConstants.CHARGE_CHARGE_TYPE_COURSE);
        details.setItemId(record.getCourseId());
        details.setItemName(record.getCourseName());
        details.setQuantity(record.getQuantity());
        details.setPrice(record.getPrice());
        details.setTotalPrice(record.getTotalPrice());
        BusinessUtil.appendRecord(details);
        chargeDetailsRepository.save(details);
    }

    @Override
    @Transactional
    public Result doDeleteById(Long id) {
        Result result = new Result();
        result.setCode(CommonConstants.SUCCESS);
        result.setMsg("删除成功");
        // 校验删除条件
        boolean check = checkDelete(id);
        if(!check){
            result.setCode(CommonConstants.FAILURE);
            result.setMsg("购买成功后不能删除");
            return result;
        }
        // 逻辑删除
        treatPlanCourseRepository.delete(id);
        // 删除疗程明细
        treatPlanCourseDetailsRepository.deleteByCourseId(id);
        // 删除待收费
        chargeDetailsRepository.deleteByBusinessIdAndChargeType(id, StateConstants.CHARGE_CHARGE_TYPE_COURSE);
        return result;
    }

    public boolean checkDelete(Long id){
        boolean check = true;
        TreatPlanCourse record = treatPlanCourseRepository.findOne(id);
        // 已付款不能删除
        if(record.getChargeStatus() == StateConstants.CHARGE_STATUS_YES){
            check = false;
        }
        return check;
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update treat_plan_course set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
    }
}
